from django.http import JsonResponse
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication

from api.models import UserInfo
from api.utils.jwt_createa_and_verified import get_payload


class Authtication(BaseAuthentication):
    """用户认证类"""
    def authenticate(self,request):
        token = request.query_params.get('token')
        verified_payload = get_payload(token)
        # 认证失败
        if not verified_payload['status']:
            raise exceptions.AuthenticationFailed(verified_payload)
        # 如果想要request.user等于用户对象，此处可以根据payload去数据库中获取用户对象。
        user = UserInfo.objects.filter(id=verified_payload.get('data').get('user_id')).first()
        request.user = user
        # 一个给request.user,一个给request.auth
        return (request.user,token)

    # 继承BaseAuthentication后，就不用写这个方法了

    # def authenticate_header(self,a):
    #     pass